import { ThreadBase } from 'lite-ts-thread';
import { TreePSD } from 'psd';

import { ButtonConverter } from './button';
import { CanvasConverter } from './canvas';
import { EditBoxConverter } from './edit-box';
import { GridConverter } from './grid';
import { LabelConverter } from './label';
import { LangLabelConverter } from './lang-label';
import { PanelConverter } from './panel';
import { ProgressBarConverter } from './progress-bar';
import { ProgressBarFilledConverter } from './progress-bar-filled';
import { SafeButtonConverter } from './safe-button';
import { SlicedSpriteConverter } from './sliced-sprite';
import { SpriteConverter } from './sprite';
import { TabConverter } from './tab';
import { ToggleConverter } from './toggle';
import { AssertServiceBase, ConverterFactoryBase, FileFactoryBase, IConverter } from '../../contract';
import { enum_ } from '../../model';

const prefixCtors: any[] = [
    EditBoxConverter,
    ButtonConverter,
    GridConverter,
    ProgressBarConverter,
    ProgressBarFilledConverter,
    SafeButtonConverter,
    SlicedSpriteConverter,
    TabConverter,
    ToggleConverter,
];

class EmptyConverter implements IConverter {
    public constructor(
        private m_TreePSD: TreePSD,
    ) { }

    public async convert() {
        const exportPSD = this.m_TreePSD.export();
        if (exportPSD.visible)
            console.log(`无法转换: ${JSON.stringify(exportPSD)}`);
        return null;
    }
}

export class ConverterFactory extends ConverterFactoryBase {
    public constructor(
        private m_AssertService: AssertServiceBase,
        private m_FileFactory: FileFactoryBase,
        private m_Thread: ThreadBase,
        offsetX: number,
        offsetY: number,
    ) {
        super(offsetX, offsetY);
    }

    public build(treePSD: TreePSD): IConverter {
        const isRoot = treePSD.isRoot();
        if (isRoot)
            return new CanvasConverter(this.m_Thread, this.m_AssertService, this, this.m_FileFactory, treePSD);

        const exportPSD = treePSD.export();
        let converterCtor: any;
        if (exportPSD.visible) {
            if (exportPSD.type == enum_.PsdLayerType.layer) {
                if (exportPSD.text) {
                    converterCtor = exportPSD.name.startsWith(LangLabelConverter.prefix) ? LangLabelConverter : LabelConverter;
                } else {
                    converterCtor = SpriteConverter;
                }
            } else {
                converterCtor = prefixCtors.find(r => {
                    return exportPSD.name.startsWith(r.prefix);
                });
                converterCtor ??= PanelConverter;
            }

            return new converterCtor(this.m_AssertService, this, this.m_FileFactory, treePSD);
        }

        return new EmptyConverter(treePSD);
    }
}